package com.mnxiaotu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mnxiaotu.common.constant.Constant;
import com.mnxiaotu.common.vo.Result;
import com.mnxiaotu.entity.PageBean;
import com.mnxiaotu.entity.Role;
import com.mnxiaotu.entity.User;
import com.mnxiaotu.entity.UserRole;
import com.mnxiaotu.service.RoleService;
import com.mnxiaotu.service.UserRoleService;
import com.mnxiaotu.service.UserService;
import com.mnxiaotu.util.DateUtil;
import com.mnxiaotu.util.StringUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.util.*;

/**
 * @author 86182
 */
@RestController
@RequestMapping("/sys/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Value("${avatarImagesFilePath}")
    private String avatarImagesFilePath;


    /**
     * 添加或者修改
     * @param user
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('system:user:add')"+"||"+"hasAuthority('system:user:edit')")
    public Result save(@RequestBody User user){
        if(user.getId() == null || user.getId() == -1){
            user.setCreateTime(new Date());
            user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
            userService.save(user);
        }else{
            user.setUpdateTime(new Date());
            userService.updateById(user);
        }
        return Result.ok();
    }

    /**
     * 修改密码
     * @param user
     * @return
     */
    @PostMapping("/updateUserPwd")
    @PreAuthorize("hasAuthority('system:user:edit')")
    public Result updateUserPwd(@RequestBody User user){
        User currentUser = userService.getById(user.getId());
        if(bCryptPasswordEncoder.matches(user.getOldPassword(),currentUser.getPassword())){
            currentUser.setPassword(bCryptPasswordEncoder.encode(user.getNewPassword()));
            currentUser.setUpdateTime(new Date());
            userService.updateById(currentUser);
            return Result.ok();
        }else{
            return Result.error("原密码错误！");
        }
    }

    /**
     * 上传用户头像图片
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/uploadImage")
    @PreAuthorize("hasAuthority('system:user:edit')")
    public Map<String,Object> uploadImage(MultipartFile file)throws Exception{
        Map<String,Object> resultMap=new HashMap<>();
        if(!file.isEmpty()){
            //获取上传文件的原始文件名
            String originalFilename = file.getOriginalFilename();
            //获取文件名的后缀名
            String suffixName=originalFilename.substring(originalFilename.lastIndexOf("."));
            //防止重名
            String newFileName= DateUtil.getCurrentDateStr()+suffixName;
            //将上传的文件内容拷贝到指定路径下的新文件中
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File(avatarImagesFilePath + newFileName));
            resultMap.put("code",0);
            resultMap.put("msg","上传成功");
            //封装上传成功后返回前端的数据信息
            Map<String,Object> dataMap=new HashMap<>();
            dataMap.put("title",newFileName);
            dataMap.put("src","userAvatar/"+newFileName);
            resultMap.put("data",dataMap);
        }
        return resultMap;
    }
    /**
     * 修改用户头像
     * @param user
     * @return
     */
    @RequestMapping("/updateAvatar")
    @PreAuthorize("hasAuthority('system:user:edit')")
    public Result updateAvatar(@RequestBody User user){
        User currentUser = userService.getById(user.getId());
        currentUser.setUpdateTime(new Date());
        currentUser.setAvatar(user.getAvatar());
        userService.updateById(currentUser);
        return Result.ok();
    }

    /**
     * 根据条件分页查询用户信息
     * @param pageBean
     * @return
     */
    @PostMapping("/list")
    @PreAuthorize("hasAuthority('system:user:query')")
    public Result list(@RequestBody PageBean pageBean){
        //获取查询条件
        String query = pageBean.getQuery().trim();
        //根据查询条件查询后分页
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>().like(StringUtil.isNotEmpty(query),"username",query);
        Page<User> pageResult = userService.page(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()),userQueryWrapper);
        //返回分页后的数据集合
        List<User> userList = pageResult.getRecords();
        for(User user:userList){
            //取得用户的角色集合并保存
            List<Role> roleList = roleService.list(new QueryWrapper<Role>
                    ().inSql("id", "select role_id from user_role where user_id=" +
                    user.getId()));
            user.setRoleList(roleList);
        }
        //前端返回分页结果
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("userList",userList);
        resultMap.put("total",pageResult.getTotal());
        return Result.ok(resultMap);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:user:query')")
    public Result findById(@PathVariable(value = "id")Integer id){
        User user = userService.getById(id);
        Map<String,Object> map=new HashMap<>();
        map.put("user",user);
        return Result.ok(map);
    }

    /**
     * 验证用户名
     * @param user
     * @return
     */
    @PostMapping("/checkUserName")
    @PreAuthorize("hasAuthority('system:user:query')")
    public Result checkUserName(@RequestBody User user){
        //判断用户名是否重复
        if(userService.getByUsername(user.getUsername())==null){
            return Result.ok();
        }else{
            return Result.error();
        }
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('system:user:delete')")
    public Result delete(@RequestBody Long[] ids){
        userService.deleteByIds(Arrays.asList(ids));
        // 删除用户角色关联表中与这些用户相关的记录
        userRoleService.remove(new QueryWrapper<UserRole>().in("user_id", ids));
        return Result.ok();
    }

    /**
     * 重置密码
     * @param id
     * @return
     */
    @GetMapping("/resetPassword/{id}")
    @PreAuthorize("hasAuthority('system:user:edit')")
    public Result resetPassword(@PathVariable(value = "id")Integer id){
        User user = userService.getById(id);
        //默认密码
        user.setPassword(bCryptPasswordEncoder.encode(Constant.DEFAULT_PASSWORD));
        user.setUpdateTime(new Date());
        userService.updateById(user);
        return Result.ok();
    }

    /**
     * 更新status状态
     * @param id
     * @param status
     * @return
     */
    @GetMapping("/updateStatus/{id}/status/{status}")
    @PreAuthorize("hasAuthority('system:user:edit')")
    public Result updateStatus(@PathVariable(value = "id")Integer id,@PathVariable(value = "status")String status){
        User user = userService.getById(id);
        user.setStatus(status);
        userService.saveOrUpdate(user);
        return Result.ok();
    }

    /**
     * 用户角色授权
     * @param userId
     * @param roleIds
     * @return
     */
    @Transactional
    @PostMapping("/grantRole/{userId}")
    @PreAuthorize("hasAuthority('system:user:role')")
    public Result grantRole(@PathVariable("userId") Long userId,@RequestBody Long[]
            roleIds){
        List<UserRole> userRoleList=new ArrayList<>();
        Arrays.stream(roleIds).forEach(r -> {
            UserRole userRole = new UserRole();
            userRole.setRoleId(r);
            userRole.setUserId(userId);
            userRoleList.add(userRole);
        });
        //将关联表中的数据清空
        userRoleService.remove(new QueryWrapper<UserRole>().eq("user_id",userId));
        //存入新的角色列表数据
        userRoleService.saveBatch(userRoleList);
        return Result.ok();
    }
}
